package com.googlecode.garbagecan.springsecuritystudy.provider;

import java.util.HashMap;
import java.util.Map;

import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationServiceException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;

public class MyAuthenticationProvider implements AuthenticationProvider {

	private Map<String, String> users = null;
	
	private UserDetailsService userDetailsService;
	
	public MyAuthenticationProvider() {
		users = new HashMap<String, String>();
		users.put("admin", "admin");
		users.put("user", "user");
		users.put("user0", "user0");
		users.put("user10", "user10");
	}
	
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		String userName = authentication.getName();
		Object principal = authentication.getPrincipal();
		Object password = authentication.getCredentials();
		System.out.println("principal: " + principal);
		System.out.println("password: " + password);

		if (!authentication.isAuthenticated()) {
			return authentication;
		}

		UserDetails user = userDetailsService.loadUserByUsername(userName);
		System.out.println("user: " + user);
		if (user == null) {
			throw new AuthenticationServiceException("Cannot load user info from UserDetailsService!");
		}
		authentication = new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), user.getAuthorities());
		return authentication;
	}
	
	public boolean supports(Class authentication) {
		return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
	}

	public UserDetailsService getUserDetailsService() {
		return userDetailsService;
	}

	public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

}
